<template>
  <div class="wrap">
    <img :src="qrImg" alt="" class="qrcode" v-if="qrImg" />
    <img :src="qrImg" alt="" class="qrcode qrcode_right" v-if="qrImg" />

    <!-- <button id="fullscreenBtn">全屏</button> -->
    <div class="worship-item" :class="[infoData.InteractiveMode == 1 ? 'start_bg' : '']" :id="`box_${index}`"
      v-for="(item, index) in boxList" :key="index">
      <div class="text-wrap">
        <p class="left">{{ item.ForwhomName }}：</p>
        <p class="content">{{ item.QifuContent }}</p>
        <p class="right">{{ item.QifuName }}</p>
      </div>
    </div>
    <img :src="infoData.BackgroundMaterialShow" id="img_mater" class="mater" ref="materialImg"
      v-if="infoData.isMaterialImg" />
    <video id="videoBox" class="mater" ref="materialVideo" controls autoplay loop preload="auto"
      :src="infoData.BackgroundMaterialShow" v-if="infoData.isMaterialVideo">
    </video>

    <img :src="infoData.BackgroundImageShow" class="wrap_bg video_bg" v-if="infoData.isBackImg" />
    <audio class="audio_wrap" ref="audioref" :src="`${baseUrl}/${infoData.backgroundMusic}`" controls autoplay loop>
    </audio>
    <video class="video_bg" :src="infoData.BackgroundImageShow" autoplay loop v-if="!infoData.isBackImg">
    </video>
  </div>
</template>
<script setup name="worship">
import QRCode from 'qrcode'
import axios, { baseUrl, webBaseUrl } from '../utils/http'
import { onMounted, ref, onBeforeUnmount, watch, nextTick } from 'vue';
import gsap from "gsap";

const infoData = ref({})
const qrImg = ref('')
const boxList = ref([])
let animations = [];
let timer = null
const lid = ref(0)
const audioref = ref(null)

const props = defineProps({
  data: {
    type: Object,
    default: () => { }
  }
})

// With async/await
const generateQR = async text => {
  try {
    const qr = await QRCode.toDataURL(text)
    console.log('qr', qr)
    qrImg.value = qr;
  } catch (err) {
    console.error(err)
  }
}

watch(() => props.data, async (val, old) => {
  if (Object.keys(val).length) {
    const obj = { ...val };
    obj.BackgroundImageShow = baseUrl + '/' + obj.BackgroundImage;
    if (obj.BackgroundMaterial) {
      obj.BackgroundMaterialShow = baseUrl + '/' + obj.BackgroundMaterial;
    }
    //console.log('obj-worship', obj)
    //测试
    //obj.InteractiveMode = 1;
    infoData.value = obj;
    const rurl = `${webBaseUrl}/#/?cid=${obj.CeremonyOrdersID}&tid=${obj.ID}`;
    console.log('rurl', rurl)
    generateQR(rurl)
    // await nextTick();
    // if (audioref.value) {
    //   audioref.value.volume = 0.2
    // }

  }
}, {
  deep: true,
  immediate: true
})

// const boxList = ref([{
//    "forwhomName":"",
//   "interactiveType": 0,
//   "QifutoName": "李四",
//   "QifuContent": "哦哦哦哦哦哦"
// },{
//   "interactiveType": 0,
//   "QifutoName": "李四ww",
//   "QifuContent": "kkkk"
// }]);





// 获取大屏互动内容
const getInteractivecontent = async () => {
  if (!infoData.value.CeremonyOrdersID) return;
  try {
    const res = await axios.getAjaxFn('/SZ_CeremonyOrders/GetInteractivecontent', {
      CeremonyOrdersID: infoData.value.ID,
      ID: lid.value
    })

    if (res.length != boxList.value.length) {
      boxList.value = res;
      animations = []
      await nextTick()
      worshipAnimate()
    }
    // console.log('getInteractivecontent',res, boxList.value)

  } catch (error) {
    console.log('getTemplateIdFn', error)
  }

}

// 修改后的动画逻辑
// function worshipAnimate() {
//   const OPTIMIZE_THRESHOLD = 15; // 性能阈值
//   const winWidth = window.innerWidth; // 提前获取窗口尺寸

//   // 先清理旧动画
//   animations.forEach(anim => anim.kill());
//   animations = [];

//   boxList.value.forEach((item, index) => {
//     const element = document.querySelector(`#box_${index}`);
//     let repeatCount = 0; // 添加一个计数器
//     // 预计算路径
//     const path = {
//       startX:  getRandomX(),
//       endX:  getRandomX() + (Math.random() * 100 - 50),
//       startY: infoData.value.HighResolution,
//       endY: -infoData.value.HighResolution - 160
//     };

//     // 硬件加速
//     gsap.set(element, {
//       willChange: "transform",
//       force3D: true
//     });

//     const animation = gsap.fromTo(element,
//       {
//         x: path.startX,
//         y: path.startY,
//       },
//       {
//         duration: boxList.value.length > OPTIMIZE_THRESHOLD ? 15 : 10,
//         y: path.endY,
//         x: path.endX,
//         ease: "linear",
//         delay: index * 0.3, // 增加间隔延迟
//         repeat: -1,
//         //repeatRefresh: true, // 重置起始值
//         onStart() {
//           //element.style.display = 'block';
//         },
//         onRepeat() {
//           repeatCount++;

//          // 批量属性更新
//          gsap.set(element, {
//             x: () => getRandomX(),//getOptimizedRandomX(index),
//             y: infoData.value.HighResolution
//           });


//         }
//       }
//     );

//     // 降低更新频率
//     // if(boxList.value.length > OPTIMIZE_THRESHOLD){
//     //   animation.timeScale(1.2);
//     //   animation.delay(index * 0.5);
//     // }

//     animations.push(animation);
//   });
// }


// const getRandomX = () => {
//       const random = Math.random();
//       let position;
//       const screenWidth = window.innerWidth; // 提前获取窗口尺寸
//       if (random < 0.3) {
//         // 0 到 0.3：随机在 20 到 300 之间
//         position = Math.random() * (300 - 20) + 20; // 20 到 300 之间
//       } else if (random > 0.3 && random <= 0.8) {
//         // 0.31 到 0.6：随机在中间区域
//         position = Math.random() * (screenWidth / 2) + (screenWidth / 4); // 中间区域
//       } else {
//         // 大于 0.6：随机在右侧
//         position = Math.random() * (screenWidth / 2) + (screenWidth / 2); // 右半部分
//       }
//       return position;
// };

function worshipAnimate() {
  boxList.value.forEach((item, index) => {
    const screenWidth = window.innerWidth;
    const screenHeight = window.innerHeight;

    // const initialX = Math.random() * screenWidth - screenWidth / 2; // 覆盖整个屏幕宽度的初始 X 轴位置
    // const resX = initialX <= 0 ? Math.random() * screenWidth + index *10 : initialX - index *10
    // 定义一个函数来生成随机位置，偏向左边和中间
    const getRandomX = () => {
      const random = Math.random();
      let position;

      if (random < 0.3) {
        // 0 到 0.3：随机在 20 到 300 之间
        position = Math.random() * (300 - 20) + 20; // 20 到 300 之间
      } else if (random > 0.3 && random <= 0.8) {
        // 0.31 到 0.6：随机在中间区域
        position = Math.random() * (screenWidth / 2) + (screenWidth / 4); // 中间区域
      } else {
        // 大于 0.6：随机在右侧
        position = Math.random() * (screenWidth / 2) + (screenWidth / 2); // 右半部分
      }

      console.log(`Generated position for index ${index}: ${position}`); // 记录位置
      return position;
    };

    //const initialX = Math.random() * screenWidth / 4 - 100; // 控制初始位置接近左侧，不跑出屏幕
    let initialX = Math.random() * screenWidth; // 随机位置，允许在边缘偏移
    //let resX = initialX + Math.random() * 50 + index * 10; // 控制偏移量，不超出视口宽度
    let resX = Math.random() * 50 + index * 10; // 控制偏移量，不超出视口宽度


    const finalY = -infoData.value.HighResolution - 160;
    const element = document.querySelector(`#box_${index}`);
    gsap.set(element, { x: getRandomX(), y: infoData.HighResolution });
    const animation = gsap.fromTo(element,
      {
        x: getRandomX(),  // 初始 X 轴位置
        y: infoData.value.HighResolution
      },
      {
        duration: 40,
        y: finalY, // Y 轴移动到视口之外
        x: () => getRandomX(), // 结束时的 X 轴随机偏移量
        //opacity: 1,   // 最终透明度
        ease: "linear",
        delay: index, // 每个元素有稍微的延迟开始
        repeat: -1, // 无限重复动画
        //yoyo: true, // 动画来回播放
        onStart() {
          // 动画开始时设置 display: block
          //element.style.display = 'block';
        },
        onComplete() {
          console.log('Animation complete for:', index);
          //element.style.display = 'none';
          //boxList.value[index].flag = true
        },
        onRepeat() {
          // 重置元素位置，确保重复动画从左侧一点开始
          //const newInitialX = Math.random() * screenWidth - 50;
          //resX = initialX + Math.random() * 50 + index * 10;
          //console.log('repeat', initialX)
          // element.style.x = initialX;
          // element.style.y = 0;

          gsap.set(element, { x: getRandomX(), y: infoData.value.HighResolution });
          console.log('repeat', getRandomX())
        },
      }
    );

    animations.push(animation)
  });
  console.log('a', animations)

}

// let isAnimating = false;
// // 获取大屏互动内容
// const getInteractivecontent = async () => {
//   if (!infoData.value.CeremonyOrdersID) return;
//   try {
//     const res = await axios.getAjaxFn('/SZ_CeremonyOrders/GetInteractivecontent', {
//       CeremonyOrdersID: infoData.value.ID,
//       ID: lid.value
//     })

//      // 保存原来的 ID 列表
//      const oldIds = new Set(boxList.value.map(item => item.ID));
//     // 找出 res 中新增的元素
//     // const newItems = res.filter(item => !oldIds.has(item.ID));
//     // const newIDs = new Set(newItems.map(item => item.ID));

//     //console.log("🔸 新增的数据：",oldIds, newItems);

//     if (res.length != boxList.value.length) {
//       if (res.length % 5 == 1) {
//         animations.forEach(anim => {
//           // if (newIDs.has(anim.vars.myID)) {
//           //   anim.kill();
//           // }
//           anim.kill();
//         });
//       }
//       animations = [];
//       isAnimating = false;
//       boxList.value = res;
//       await nextTick()
//       setTimeout(() => {
//         worshipAnimate(res.length)
//       },200)
//     }

//   } catch (error) {
//     console.log('getTemplateIdFn', error)
//   }

// }



// function getNonOverlappingX(indexInGroup, groupSize) {
//   const screenWidth = window.innerWidth;
//   const sectionWidth = screenWidth / groupSize;
//   const padding = 40;

//   const baseX = indexInGroup * sectionWidth + sectionWidth / 2;
//   //const variation = (sectionWidth / 2 - padding) * (Math.random() - 0.5); // -~+ 随机偏移
//   const variationRange = Math.min(sectionWidth / 2 - padding, 60); // 限制偏移最大60px
//   const variation = variationRange * (Math.random() - 0.5);

//   return baseX + variation;
// }


// function worshipAnimate(total) {
//   if (isAnimating) return;
//   isAnimating = true;
//   const GROUP_SIZE = 5;
//   //const total = boxList.value.length;
//   const groupCount = Math.ceil(total / GROUP_SIZE);
//   //console.log('groupCount',groupCount)
//   let currentGroupIndex = 0;
//   const DURATION = 20; // 动画总时长
//   const OVERLAP_TRIGGER_Y = window.innerHeight * 0.24;
  

//   // 所有元素先隐藏
//   boxList.value.forEach((_, index) => {
//     const el = document.querySelector(`#box_${index}`);
//     if (el) {
//       gsap.set(el, { opacity: 0 });
//     }
//   });
 
//   const playGroup = () => {
//     //console.log('✅ 所有组播放完成');
//     if (currentGroupIndex >= groupCount && groupCount> 1) {
//       //console.log('update',groupCount)
//       currentGroupIndex = 0;
//       playGroup(); // ✅ 继续循环播放
//       return;
//     }
//    // console.log(`▶️ 播放第 ${currentGroupIndex + 1} 组 / 共 ${groupCount} 组`);

//   const startIndex = currentGroupIndex * GROUP_SIZE;
//   const endIndex = Math.min(startIndex + GROUP_SIZE, total);
//   let finishedCount = 0;
//   let overlapStarted = false; // 控制 overlap 只触发一次

//   for (let i = startIndex; i < endIndex; i++) {
//     const el = document.querySelector(`#box_${i}`);
//     if (!el) continue;

//     const groupIndex = i - startIndex; // 在组内的索引

//     const startX = getNonOverlappingX(groupIndex, GROUP_SIZE);
//     const endX = startX + (Math.random() * 100 - 50);

//     const path = {
//       startX,
//       endX,
//       //startY: infoData.value.HighResolution,
//       startY: 200,
//       //endY: -infoData.value.HighResolution - 400
//       endY: -infoData.value.HighResolution - 200
//     };

//     gsap.set(el, {
//       x: path.startX,
//       y: path.startY,
//       opacity: 1,
//       willChange: "transform",
//       force3D: true
//     });

//     const anim = gsap.to(el, {
//       duration:  DURATION,
//       x: path.endX,
//       y: path.endY,
//       ease: "linear",
//       myID:boxList.value[i].ID,
//       onStart: () => {
//         gsap.set(el, { opacity: 1 });
//       },
//       onUpdate: function () {
//           // 在播放到一半时，预先启动下一组（只触发一次）
//           // if (!overlapStarted && anim.time() >= (DURATION - OVERLAP_TIME)) {
//           //   overlapStarted = true;
//           //   currentGroupIndex++;
//           //   playGroup();
//         // }
//         if (!overlapStarted) {
//           const rect = el.getBoundingClientRect();
//           if (rect.top < OVERLAP_TRIGGER_Y) { // 距离顶部不到30%视口
//             //console.log('onUpdate..',el)
//             overlapStarted = true;
//             currentGroupIndex++;
//             playGroup();
//           }
//         }
//       },
//       onComplete: () => {
//         const rect = el.getBoundingClientRect();
//         if (rect.top < OVERLAP_TRIGGER_Y) { 
//           console.log('onComplete..', el)
//           gsap.set(el, { opacity: 0 });
//           //animations = []
//         }
       
//         //gsap.set(el, { opacity: 0 });
//         finishedCount++;
//         if (finishedCount === endIndex - startIndex) {
//           //console.log('onComplete...',finishedCount)
          
//           if (groupCount === 1) {
//             //console.log('onComplete...groupCount',groupCount)
//             currentGroupIndex = 0;
//             playGroup();
//           }
           
//         }
//       }
//     });

//     animations.push(anim);
//      console.log('animations',animations)
//   }
// };

//   // ✅ 首组立即播，并跳过 overlap 逻辑
//   playGroup();
// }

onMounted(async () => {

  timer = setInterval(() => {
    getInteractivecontent()
  }, 5 * 1000)
  //getInteractivecontent()
})

onBeforeUnmount(() => {
  clearInterval(timer)
  animations.forEach(animation => animation.kill());
})
</script>
<style lang="less" scoped>
@w: 1920vw;
@rw: (@w/100);
@h: 1080vh;
@rh: (@h/100);

.adaptive-size(@elementWidth, @elementHeight, @baseWidth: 1920, @baseHeight: 1080) {
  @widthRatio: (@elementWidth / @baseWidth) * 100;
  @heightRatio: (@elementHeight / @baseHeight) * 100;
  width: @widthRatio * 1vw;
  height: @heightRatio * 1vh;
}

.adaptive-font(@elementWidth, @baseWidth: 1920) {
  @widthRatio: (@elementWidth / @baseWidth) * 100;
  font-size: @widthRatio * 1vw;
}

.wrap {
  position: relative;
  width: 100%;
  height: 100vh;

  box-sizing: border-box;

  .mater {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    object-fit: contain;
    /* 确保视频填满屏幕，且保持视频比例 */
    object-position: center;
    background-color: transparent;
    /* 背景颜色，避免视频比例问题时的黑边 */
    z-index: 3;
  }
}

.worship-item {
  width: 122px;
  height: 194px;
  background: url('../assets/img/dl2.png') no-repeat;
  background-size: 100% 100%;
  position: absolute;
  bottom: 0;
  //left: 50%; // 确保初始位置是相对于屏幕中心的
  //transform: translateX(-50%); // 确保元素初始位置在屏幕两侧随机分布
  //display: none; // 初始时隐藏
  z-index: 1;
  will-change: transform;
  transform-style: preserve-3d;

  &.start_bg {
    // width: (122vw / @rw);
    // height: (122vw / @rw);
    width: 122px;
    height: 122px;
    background: url('../assets/img/start_bg.jpg') no-repeat;
    background-size: 100% 100%;
  }

  .text-wrap {
    position: absolute;
    // width: (200vw / @rw);
    width: 200px;
    height: fit-content;
    padding: 5px 10px;
    top: 70%;
    left: 50%;
    transform: translateX(-50%);
    border: 2px solid rgb(252, 135, 51);
    border-radius: 4px;
    .adaptive-font(14);
    color: #000;
    background: rgb(255, 227, 205);
    box-sizing: border-box;
    z-index: 6;

    .left {
      .adaptive-font(16);
      font-weight: bold;
    }

    .content {
      text-indent: 20px;
    }

    .right {
      text-align: right;
    }
  }

}

.qrcode {
  position: absolute;
  left: 200px;
  top: 50%;
  transform: translateY(-50%);
  width: 150px;
  height: 150px;
  z-index: 1;

  &.qrcode_right {
    left: initial;
    right: 200px;
  }
}

.video_bg {
  position: absolute;
  left: 0;
  top: 0;
  z-index: -2;
  //object-fit: cover; /* 确保视频填满屏幕，且保持视频比例 */
  background-color: transparent;
  /* 背景颜色，避免视频比例问题时的黑边 */
  /* 背景颜色，避免视频比例问题时的黑边 */
}

.audio_wrap {
  position: absolute;
  right: 0;
  top: 0;
  display: none;
}
</style>